<template>
  <div style="height: 100%;width: 100%">
    <div style="height: 60px;text-align: right; padding-right: 100px">
      <el-button @click="handleZoom(0.2)">放大</el-button>
      <el-button @click="handleZoom(-0.2)">缩小</el-button>
      <el-button @click="handleZoom(1)">复原</el-button>
    </div>
    <div  style="height:calc(100% - 60px); position: relative" >
      <div class="canvas" ref="canvas" style="height: 100%"></div>
    </div>
  </div>
</template>
<script>
  import BpmnViewer from 'bpmn-js';
  import Utils from "@/utils/utils";

  export default {
    name: 'ViewBpmn',
    props: {
      bpmnData: {
        type: String, // bpm xml文件传入，即可显示流程图
        default: ""
      }
    },
    data(){
      return {
        bpmnViewer: null,
        containerEl: null,
        scale: 1,
      }
    },
    mounted() {
      this.init();
    },
    methods:{
      init(){
        const canvas = this.$refs.canvas
        this.bpmnViewer && this.bpmnViewer.destroy();
        this.bpmnViewer = new BpmnViewer({
          container:canvas,
        });
        this.createNewDiagram();
        // 根据窗口大小变动自适应
        window.addEventListener("resize",()=>{
          const canvas = this.bpmnViewer.get('canvas');
          canvas.zoom("fit-viewport","auto")
        })
      },
      async createNewDiagram() {
        let result = await this.bpmnViewer.importXML(this.bpmnData);
        let { warnings,error } = result;
        if(error){
          console.log(warnings)
          console.log("解析流程图失败")
          this.$message.error("流程图解析失败")
        }
        const canvas = this.bpmnViewer.get('canvas');
        // // 流程图居中显示
        this.$refs.canvas.style.opacity = 0;
        setTimeout(()=>{
          canvas.zoom("fit-viewport","auto")
          this.$refs.canvas.style.opacity = 1;
          // svg 浏览器适配处理
          this.svgBrowserAdaptation();
        },500)
      },
      svgBrowserAdaptation(){
        if(Utils.isSafari()){
          let canvasHeight = this.$refs.canvas.clientHeight;
          let canvasWidth = this.$refs.canvas.clientWidth;
          let svg = this.$refs.canvas.getElementsByTagName("svg").item(1);
          svg.style.height = canvasHeight;
          svg.style.width = canvasWidth;
        }
      },
      handleZoom(flag) {
        let self = this;
        if(flag === 1){
          this.scale = 1;
          this.$nextTick(() => {
            self.bpmnViewer.get('canvas').zoom('fit-viewport',"auto");
          });
          return;
        }
        if(this.scale >= 2 && flag > 0){
          return;
        }
        if (flag < 0 && this.scale <= 1) {
          return;
        }
        this.scale += flag;
        this.$nextTick(() => {
          self.bpmnViewer.get('canvas').zoom(this.scale);
        });
      }
    }
  }
</script>